﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Chowpoo.Common;
using Chowpoo.Util;
using CourseSystem.Common;
using CourseSystem.Common.Helpers;
using CourseSystem.Common.Models;
using CourseSystem.Core.BLL;
using CourseSystem.Core.Enum;
using CourseSystem.Core.Entities;
using CourseSystem.Stat;
using CourseSystem.Stat.ActionFilter;

namespace CourseSystem.Web.Controllers
{
    public class AccountController : BaseController
    {
        [StatFilter]
        [UrlStatFilter]
        public ActionResult Logon()
        {
            return View();
        }

        [HttpPost]
        public ActionResult Logon(LogOnModel info)
        {
            if (!ModelState.IsValid)
            {
                ViewData["AlertMsg"] = "登录失败.";
                return View();
            }
            if (string.IsNullOrEmpty(info.Account) || string.IsNullOrEmpty(info.PassWord))
            {
                ViewData["AlertMsg"] = "登录失败.";
                return View();
            }

            info.Account = info.Account.Trim();
            info.PassWord = info.PassWord.Trim();

            //执行学生学号登录流程
            if (CommonUtils.IsInt(info.Account))
            {
                var user = StudentBLL.Login(info.Account, Security.Pass2Md5(info.PassWord));
                if (user != null)
                {
                    if ((RegReviewEnum)user.RegType != RegReviewEnum.Pass)
                    {
                        ViewData["AlertMsg"] = "注册未通过审核,请联系老师.";
                        return View();
                    }
                    user.LearnTimes++;
                    user.LastIp = CommonRequest.GetIP();
                    StudentBLL.Edit(user);
                    UserHelper.SetLogined(new UserModel { Id = user.Id, UserName = user.StuName, UserType = UserTypeEnum.Student, LoginTime = DateTime.Now });
                    //安全性检查
                    UrlStat.LoginSafeCheck();
                    //登录初始化
                    LearnProcessStat.Init(user.Id);
                    return RedirectToAction("Index", "Home");
                }
                ViewData["AlertMsg"] = "登录失败.";
                return View();
            }
            var teacher = TeacherBLL.Login(info.Account, Security.Pass2Md5(info.PassWord));
            if (teacher != null)
            {
                UserHelper.SetLogined(new UserModel { Id = teacher.Id, MinType = teacher.Type, IsExpert = teacher.Type == 4, UserName = teacher.Name, UserType = teacher.Type == 0 ? UserTypeEnum.Admin : UserTypeEnum.Teacher, LoginTime = DateTime.Now });
                if (teacher.Type == 4)
                    return RedirectToAction("Index", "Home");
                return RedirectToAction("Index", "Admin");
            }
            ViewData["AlertMsg"] = "登录失败.";
            return View();
        }

        [StatFilter]
        [UrlStatFilter]
        public ActionResult LogOut()
        {
            if (UserHelper.LoginUser != null)
            {
                var id = UserHelper.LoginUser.Id;
                //清理在线用户
                if (UserHelper.LoginUser.UserType > 0)
                {
                    UserOnlineStat.CommitCurrent();
                }
                //登出事件
                UrlStat.LoginSafeCheck(true);

            }
            UserHelper.LogOut();
            return RedirectToAction("Logon");
        }

        [UserAuth(IsLimt = true, UserType = UserTypeEnum.Student)]
        public ActionResult ViewLastUrl()
        {
            var info = StudentBLL.Get(UserHelper.LoginUser.Id);
            if (info == null)
                return NotFound();
            if (string.IsNullOrEmpty(info.LastUrl))
            {
                info.IsCanUpLastUrl = true;
                StudentBLL.Edit(info);
                UserHelper.UpdateStudent();
                return RedirectToAction("Index", "Home");
            }
            info.IsCanUpLastUrl = true;
            StudentBLL.Edit(info);
            UserHelper.UpdateStudent();
            return Redirect("~/" + info.LastUrl);
        }

        public ActionResult RegUc()
        {
            CommonRequest.ClearCache();
            ViewData.Model = new StudentInfo();
            return PartialView();
        }

        [HttpPost]
        public ActionResult RegUc(StudentInfo info)
        {
            CommonRequest.ClearCache();
            ViewData.Model = info;
            if (string.IsNullOrEmpty(info.PassWord) || info.PassWord.Length < 6 || info.PassWord.Length > 20)
                ModelState.AddModelError("PassWord", "请输入6-20个字符");
            if (!ModelState.IsValid)
            {
                return PartialView();
            }
            info.Uid = StudentHelper.GenNewUid(info.GradeYear, info.SubjectIdFake);
            var addInfo = new StudentInfo
                              {
                                  Uid = info.Uid,
                                  PassWord = Security.Pass2Md5(info.PassWord),
                                  ClassId = info.ClassId,
                                  GradeYear = info.GradeYear,
                                  LastIp = "",
                                  LastUrl = "",
                                  LearnTimes = 0,
                                  RegDate = DateTime.Now,
                                  RegType = (byte)RegReviewEnum.HaveNotReview,
                                  Score = -1,
                                  StuName = info.StuName.Trim(),
                                  // SubjectId = info.SubjectId,
                                  //  CollegeIdFake = info.CollegeIdFake
                              };
            if (StudentBLL.Add(addInfo))
            {
                SetHighLineMsg("注册成功!您的学号是:" + addInfo.Uid + "请等待审核..");
                return PartialView(addInfo);
            }
            SetHighLineMsg("未知错误.");
            return PartialView();
        }
        [UserAuth(UserType = UserTypeEnum.Student)]
        public ActionResult ChangePass()
        {
            return View();
        }

        [HttpPost]
        [UserAuth(UserType = UserTypeEnum.Student)]
        public ActionResult ChangePass(PassModel info)
        {
            ViewData.Model = info;
            if (!ModelState.IsValid)
                return PartialView();
            if (info.Password != info.PasswordRe)
            {
                ModelState.AddModelError("Password", "两次密码必须一致!");
                return PartialView();
            }
            var user = UserHelper.LoginUser;
            if (user.UserType == UserTypeEnum.Student)
            {
                if (StudentBLL.ChangePass(user.Id, Security.Pass2Md5(info.OldPassword), Security.Pass2Md5(info.Password)))
                {
                    SetHighLineMsg("修改成功.");
                    return PartialView();
                }
                SetHighLineMsg("修改失败!");
                return PartialView();
            }
            if (TeacherBLL.ChangePass(user.Id, Security.Pass2Md5(info.OldPassword), Security.Pass2Md5(info.Password)))
            {
                SetHighLineMsg("修改成功.");
                return PartialView();
            }
            SetHighLineMsg("修改失败!");
            return PartialView();
        }


        public ActionResult GuessLogin()
        {
            if (UserHelper.LoginUser != null)
                RedirectToAction("LogOut");
            UserHelper.SetLogined(new GuessModel());
            return RedirectToAction("Index", "Study");
        }
    }
}
